var express = require('express');
var router = express.Router();
const VALID_EMAIL_REGEX = /^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/;

/* GET home page. */
router.get('/', function(req, res, next) {
    res.render('newsletter-signup', { title: 'Newsletter Sign Up' });
});

router.post('/signup', function(req, res, next) {
    // console.log('name:'+ req.body.name);
    // console.log('email:'+ req.body.email);
    const name = req.body.name || '', email = req.body.email || '';
    if (!VALID_EMAIL_REGEX.test(email)) {
        req.session.flash = {
            type: 'is-danger',
            title: 'Validation error!',
            message: 'The email address you entered was not valid. Please try again.'
        };
        return res.redirect(303, '/newsletter/');
    }
    if (name.trim() === '' || email.trim() === '') {
        req.session.flash = {
            type: 'is-danger',
            title: 'Validation error!',
            message: 'The name and email fields are both required.'
        };
        return res.redirect(303, '/newsletter/');
    }
    res.redirect(303, '/newsletter/thank-you');
});

router.get('/thank-you', function(req, res, next) {
    res.render('newsletter-thank-you', { title: 'Thank You' });
});

module.exports = router;
